package com.integration.datahandling;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.SocketChannel;
import java.util.List;

import br.lp2p.localmessage.LocalMessageBuilder;

import com.integration.pojo.FileDTO;
/**
 * 
 * @author Ismael.Santos
 *
 *	Classe que efetua as requisicoes ao daemon LP2P atraves do protocolo local lp2p
 *	Deve ser injetada na implementacao dos servicos REST para manipulacao dos arquivos na rede lp2p, quando requisitadas via REST.
 *
 */
public class LP2PDataHandler implements IDataHandler {
	private String localAddress;
	private String localPort;
	
	
	@Override
	public InputStream getFile(String sharing, String fileId, Integer index, Integer size) throws IOException {
		ByteBuffer lGetMessageBuffer = LocalMessageBuilder.buildLGet(sharing, fileId, index.toString(), size.toString());
		SocketAddress remote =  new InetSocketAddress(localAddress, Integer.parseInt(localPort));
		SocketChannel channel = SocketChannel.open( remote );
		while (lGetMessageBuffer.hasRemaining()){
			channel.write(lGetMessageBuffer);
		}
		ByteBuffer response = ByteBuffer.allocateDirect(1024*1024*32);
		channel.read(response);
		response.flip();
		response.compact();
		
		
		InputStream in = Channels.newInputStream(channel); // FIXME: "channel" variable cannot be used here.
		return in;
	}

	@Override
	public List<FileDTO> getListOfFiles(String sharing, String filter, String condition, String value) {
		return null;
	}

	@Override
	public Integer deleteFiles(String Sharing, List<String> listOfFileId) {
		return null;
	}

	@Override
	public Integer addFile(String sharing, List<FileDTO> files) {
		return null;
	}

}